﻿using System.IO;
using System.Net;
using System.Web;

namespace YueRu.Common
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class UrlExtend
    {
        /// <summary>
        /// 返回URL中结尾的文件名
        /// </summary>
        public static string GetFilename(string url)
        {
            if (url == null)
            {
                return "";
            }
            string[] strs1 = url.Split(new[] {'/'});
            return strs1[strs1.Length - 1].Split(new[] {'?'})[0];
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }


        /// <summary>
        ///  根据Url获得源文件内容
        /// </summary>
        /// <param name="url">合法的Url地址</param>
        /// <returns></returns>
        public static string GetSourceTextByUrl(string url)
        {
            var sourceText = string.Empty;

            try
            {
                var request = WebRequest.Create(url);
                request.Timeout = 20000; //20秒超时
                var response = request.GetResponse();

                var resStream = response.GetResponseStream();
                if (resStream != null)
                {
                    sourceText = new StreamReader(resStream).ReadToEnd();
                }
            }
            catch
            {
                ;
            }
            return sourceText;
        }

        /// <summary>
        /// 获取站点根目录URL
        /// </summary>
        /// <returns></returns>
        public static string GetRootUrl(string forumPath)
        {
            var port = HttpContext.Current.Request.Url.Port;
            var scheme = HttpContext.Current.Request.Url.Scheme;
            var host = HttpContext.Current.Request.Url.Host;

            return string.Format("{0}://{1}{2}{3}", scheme, host, (port == 80 || port == 0) ? "" : ":" + port, forumPath);
        }
    }
}